<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- 引入 Toastify 库用于显示提示信息 -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        /* 顶部导航栏样式 */
        .top-navbar {
            background-color: #333;
            color: white;
            display: flex;
            align-items: center;
            padding: 10px 20px;
        }

        .top-navbar a {
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            transition: background-color 0.3s;
        }

        .top-navbar a:hover {
            background-color: #555;
        }

        .top-navbar a.active {
            background-color: #007BFF;
        }

        /* 让退出登录按钮更靠右 */
        .top-navbar #logout-btn {
            margin-left: auto;
        }

        /* 侧边栏样式 */
        .side-navbar {
            background-color: #f4f4f4;
            width: 200px;
            height: calc(100vh - 50px);
            overflow-y: auto;
            border-right: 1px solid #ddd;
        }

        .side-navbar ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        .side-navbar li {
            padding: 15px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .side-navbar li:hover {
            background-color: #e0e0e0;
        }

        .side-navbar li.active {
            background-color: #007BFF;
            color: white;
        }

        /* 内容区域样式 */
        .main-content {
            flex: 1;
            display: flex;
        }

        .content-container {
            flex: 1;
            padding: 20px;
        }

        .content {
            display: none;
        }

        .content.active {
            display: block;
        }

        /* 小屏幕样式 */
        @media (max-width: 768px) {
            .side-navbar {
                display: none;
            }
            .content-container {
                margin-left: 0;
            }
        }

        /* 新增的侧边栏切换按钮样式 */
        .sidebar-toggle-btn {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            color: white;
            cursor: pointer;
            margin-right: 10px;
        }

        @media (max-width: 768px) {
            .sidebar-toggle-btn {
                display: block;
            }
        }

        /* 搜索框样式 */
        .search-container {
            margin: 0 auto; /* 将搜索框居中 */
        }

        input[type="text"] {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-right: 10px;
        }

        button {
            padding: 8px 16px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
<!-- 顶部导航栏 -->
<div class="top-navbar">
    <a href="/home" id="home-btn">主页</a>
    <button class="sidebar-toggle-btn" id="sidebar-toggle-btn">&#9776;</button>
    <!-- 搜索区域 -->
    <div class="search-container">
        <input type="text" id="searchInput" placeholder="输入关键词搜索">
        <button onclick="searchContent()">搜索</button>
    </div>
    <a href="#" id="logout-btn">退出登录</a>
</div>
<!-- 主体内容布局 -->
<div class="main-content">
    <!-- 侧边栏 -->
    <nav class="side-navbar" id="side-navbar">
        <ul>
            <li data-target="User_management">用户管理</li>
            <li data-target="Song_list">歌曲查询</li>
            <li data-target="Star_list">明星列表</li>
            <li data-target="Follow_list">关注列表</li>
            <li data-target="Perimeter_list">周边列表</li>
            <li data-target="Favorite_list">收藏列表</li>
            <li data-target="ShoppingCart_list">购物车列表</li>
            <li data-target="BuyNow_list">订单列表</li>
            <li data-target="FeedBack_list">反馈列表</li>
            <li data-target="Reply_list">回复列表</li>
        </ul>
    </nav>
    <!-- 内容区域 -->
    <div class="content-container">
        <div id="User_management" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Song_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Star_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Follow_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Perimeter_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Favorite_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="ShoppingCart_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="BuyNow_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="FeedBack_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
        <div id="Reply_list" class="content">
            <!-- 这里用于显示加载的内容 -->
        </div>
    </div>
</div>

<script>
    // 显示 Toast 提示信息
    function showToast(message, type ='success') {
        Toastify({
            text: message,
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: type ==='success'? "green" : "red",
        }).showToast();
    }

    // 处理 URL 哈希变化
    function handleHashChange() {
        const hash = window.location.hash.slice(1);
        const [targetId, query] = hash.split('?');
        let page = 1;
        if (query) {
            const pageParam = query.split('=')[1];
            page = parseInt(pageParam);
            if (isNaN(page) || page <= 0) {
                page = 1;
            }
        }

        const navItem = document.querySelector(`.side-navbar li[data-target="${targetId}"]`);
        if (navItem) {
            const currentPage = parseInt(localStorage.getItem(`${targetId}_currentPage`)) || 1;
            if (page!== currentPage) {
                navItem.click();
                loadContent(targetId, page);
            }
        }
    }

    // 使用对象映射来拼接 URL
    const urlMap = {
        'User_management': `/userlist?page=`,
        'Song_list': `/songlist?page=`,
        'Star_list': `/star-list?page=`,
        'Follow_list': `/follow-list?page=`,
        'Perimeter_list': `/perimeter-list?page=`,
        'Favorite_list': `/favorite-list?page=`,
        'ShoppingCart_list': `/shoppingcart-list?page=`,
        'BuyNow_list': `/buynow-list?page=`,
        'FeedBack_list': `/feedback-list?page=`,
        'Reply_list': `/reply-list?page=`
    };

    // 封装 AJAX 请求函数
    function loadContent(targetId, page = 1) {
        let url = urlMap[targetId].replace('page=', `page=${page}`);
        console.log('请求的 URL:', url);

        $.ajax({
            url: url,
            method: 'GET',
            success: function (response) {
                console.log('返回的数据:', response);
                $(`#${targetId}`).html(response);
                // 更新 URL 哈希
                window.location.hash = `${targetId}?page=${page}`;
                // 更新 localStorage
                localStorage.setItem(`${targetId}_currentPage`, page);
                localStorage.setItem('activePage', targetId);
            },
            error: function (error) {
                if (error.status === 401) {
                    // 未登录，跳转登录页
                    window.location.href = '/login';
                } else {
                    console.error(`Error loading ${url}:`, error);
                    showToast(`Error loading ${targetId}`, 'error');
                }
            }
        });
    }

    // 默认打开管理者标签页
    window.addEventListener('load', () => {
        const activePage = localStorage.getItem('activePage');
        if (activePage) {
            const activeNavItem = document.querySelector(`.side-navbar li[data-target="${activePage}"]`);
            if (activeNavItem) {
                activeNavItem.click();
                const page = parseInt(localStorage.getItem(`${activePage}_currentPage`)) || 1;
                loadContent(activePage, page);
            }
        } else {
            // 初次登录，默认打开用户管理页面
            const defaultTargetId = 'User_management';
            const defaultPage = parseInt(localStorage.getItem(`${defaultTargetId}_currentPage`)) || 1;
            const userManagementItem = document.querySelector(`.side-navbar li[data-target="${defaultTargetId}"]`);
            if (userManagementItem) {
                userManagementItem.click();
                loadContent(defaultTargetId, defaultPage);
            }
        }

        // 检查 URL 哈希，如果有则处理
        if (window.location.hash) {
            handleHashChange();
        }
    });

    // 监听 URL 哈希变化
    window.addEventListener('hashchange', handleHashChange);

    const navItems = document.querySelectorAll('.side-navbar li');
    const contents = document.querySelectorAll('.content');

    navItems.forEach(item => {
        item.addEventListener('click', () => {
            navItems.forEach(navItem => navItem.classList.remove('active'));
            item.classList.add('active');

            const targetId = item.dataset.target;
            contents.forEach(content => content.classList.remove('active'));
            document.getElementById(targetId).classList.add('active');

            const page = parseInt(localStorage.getItem(`${targetId}_currentPage`)) || 1;
            loadContent(targetId, page);
        });
    });

    // 处理分页点击事件
    $(document).off('click', '.pagination a').on('click', '.pagination a', function (e) {
        e.preventDefault();
        const targetId = $('.content.active').attr('id');
        const page = parseInt($(this).data('page'));
        if (!isNaN(page) && page > 0) {
            console.log('点击的页码:', page);
            loadContent(targetId, page);
        } else {
            showToast('无效的页码', 'error');
        }
    });

    // 处理表单提交事件
    $(document).on('submit', 'form', function (e) {
        e.preventDefault();
        const form = $(this);
        const url = form.attr('action');
        const method = form.attr('method');
        const data = form.serialize();

        $.ajax({
            url: url,
            method: method,
            data: data,
            success: function (response) {
                const targetId = $('.content.active').attr('id');
                $(`#${targetId}`).html(response);
                showToast('表单提交成功');
            },
            error: function (error) {
                if (error.status === 401) {
                    window.location.href = '/login';
                } else {
                    console.error('表单提交错误:', error);
                    showToast('表单提交错误', 'error');
                }
            }
        });
    });

    // 处理删除操作
    $(document).on('click', '.delete-btn', function (e) {
        e.preventDefault();
        if (confirm('确定要删除该项吗？')) {
            const url = $(this).attr('href');
            $.ajax({
                url: url,
                method: 'DELETE',
                success: function (response) {
                    const targetId = $('.content.active').attr('id');
                    $(`#${targetId}`).html(response);
                    showToast('项目删除成功');
                },
                error: function (error) {
                    if (error.status === 401) {
                        window.location.href = '/login';
                    } else {
                        console.error('删除项目错误:', error);
                        showToast('删除项目错误', 'error');
                    }
                }
            });
        }
    });

    // 处理退出登录点击事件
    document.getElementById('logout-btn').addEventListener('click', function () {
        // 清除相关的 localStorage 数据
        const keys = Object.keys(localStorage);
        keys.forEach(key => {
            localStorage.removeItem(key);
        });
        // 跳转到登录页面
        window.location.href = '/login';
    });

    // 给主页按钮添加点击事件监听
    document.getElementById('home-btn').addEventListener('click', function () {
        const userManagementItem = document.querySelector(`.side-navbar li[data-target="User_management"]`);
        if (userManagementItem) {
            userManagementItem.click();
        }
    });

    // 搜索功能
    function searchContent() {
        const keyword = document.getElementById('searchInput').value.toUpperCase();
        const activeContent = document.querySelector('.content.active');
        const rows = activeContent.getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            const cells = rows[i].getElementsByTagName('td');
            let match = false;
            for (let j = 0; j < cells.length; j++) {
                const cellText = cells[j].textContent || cells[j].innerText;
                if (cellText.toUpperCase().indexOf(keyword) > -1) {
                    match = true;
                    break;
                }
            }
            if (match) {
                rows[i].style.display = '';
            } else {
                rows[i].style.display = 'none';
            }
        }
    }

    // 侧边栏切换按钮点击事件
    document.getElementById('sidebar-toggle-btn').addEventListener('click', function () {
        const sideNavbar = document.getElementById('side-navbar');
        if (sideNavbar.style.display === 'none' || sideNavbar.style.display === '') {
            sideNavbar.style.display = 'block';
        } else {
            sideNavbar.style.display = 'none';
        }
    });
</script>
</body>

</html>